// import fetch from 'dva/fetch';
import axios from 'axios';
import jsonp from 'jsonp';
import lodash from 'lodash';
import pathToRegexp from 'path-to-regexp';
import {message} from 'antd';
import {CORS,YQL} from './config';

const fetch = (options) => {
  let {method='get', data, fetchType, url} = options

  const cloneData = lodash.cloneDeep(data)

  try {
    let domin = ''
    const match = pathToRegexp.parse(url)
    url = pathToRegexp.compile(url)(data)
    for(let item of match){
      if(item instanceof Object && item.name in cloneData){
        delete cloneData[item.name]
      }
    }
    url = domin + url
  }catch(e){
    message.error(e.message)
  }

  if (fetchType==='JSONP'){
    return new Promise((resolve, reject)=>{
      jsonp(url,{
        param: `${qs.stringify(data)}&callback`,
        name: `jsonp_${new Date().getTime()}`,
        timeout: 40000,
      },(error, result)=>{
        if(error){
          reject(error)
        }
        resolve({statusText:'OK', status: 200, data: result})
      })
    })
  }
  switch(method.toLowerCase()){
    case 'get':
      return axios.get(url,{
        params: cloneData,
      })
    case 'delete':
      return axios.delete(url,{
        data:cloneData,
      })
    case 'post':
      return axios.post(url, cloneData)
    case 'put': 
      return axios.put(url, cloneData)
    default:
      return axios(options)
  }
}

export default function request (options){
  
  if(options.url && options.url.indexOf('//')> -1){
    //处理url包含http://
    const origin = `${options.url.split('//')[0]}//${options.url.split('//')[1].split('/')[0]}`

    if(window.location.origin !== origin){
      if(CORS&&CORS.indexOf(origin)>-1){
        options.fetchType = 'CORS'
      }else if(YQL && YQL.indexOf(origin)> -1){
        options.fetchType = 'SQL'
      }else{
        options.fetchType = 'JSONP'
      }
    }
  }

  return fetch(options).then((response)=>{
    const {statusText, satus} = response
    let data = options.fetchType == 'YQL' ? response.data.query.results.json: response.data

    if(data instanceof Array){
      data = {
        list: data,
      }
    }
    return {
      success: true,
      message: statusText,
      statusCode: status,
      ...data,
    }
  }).catch((error) => {
    const {response} = error
    let msg
    let statusCode
    if(response&&response instanceof Object){
      const {data, statusText} = response
      statusCode = response.status
      msg = data.message || statusText
    }else{
      statusCode = 600
      msg = error.message || 'Network Error'
    }
    return { success:false, statusCode, message: msg}
  })
}

// function parseJSON(response) {
//   return response.json();
// }

// function checkStatus(response) {
//   if (response.status >= 200 && response.status < 300) {
//     return response;
//   }

//   const error = new Error(response.statusText);
//   error.response = response;
//   throw error;
// }

// /**
//  * Requests a URL, returning a promise.
//  *
//  * @param  {string} url       The URL we want to request
//  * @param  {object} [options] The options we want to pass to "fetch"
//  * @return {object}           An object containing either "data" or "err"
//  */
// export default function request(url, options) {
//   return fetch(url, options)
//     .then(checkStatus)
//     .then(parseJSON)
//     .then(data => ({ data }))
//     .catch(err => ({ err }));
// }
